<template>
  <tiny-button size="large" @click="triggerFileInput"   >{{title}}</tiny-button>
  <div style="height: 40px;width: 40px;">
    <input
        type="file"
        ref="fileInput"
        style="display: none"
        @change="handleFileChange"
    />
  </div>
</template>
<script setup>
import {ref} from "vue";
import tool from "@/utils/tool";
const emit = defineEmits(['change'])
const fileInput = ref(null);
const file = ref(null);
const props = defineProps({
  title: {type: String,default: '导入'}
})
const triggerFileInput = () => {
  fileInput.value.click(); // 手动触发文件选择框
}
const handleFileChange = (event) => {
  file.value = event.target.files[0] // 获取选择的文件
  if (file.value) {
    uploadFile() // 自动上传文件
  }
}
const uploadFile = async () => {
  if (!file.value) {
    return tool.err('请先选择文件')
  }
  try {
    const formData = new FormData()
    formData.append('file', file.value); // 将文件添加到 FormData
    tool.post('app/upload', formData,true, 'multipart/form-data').then(ret => {
      if(ret.stat && ret.data) {
        file.value = null
        fileInput.value.value = ''
        emit('change', ret.data)
      }
    })
  } catch (error) {
    file.value = null
    fileInput.value.value = ''
    tool.err('上传失败')
  }
}

</script>
<style scoped lang="scss">

</style>